package net.qiqb.spring.autoconfig;

import jakarta.annotation.Resource;
import net.qiqb.rabbitmq.QueueNameGenerator;
import net.qiqb.rabbitmq.RabbitmqBeanPostProcessor;
import net.qiqb.rabbitmq.RabbitmqDomainEventPublisher;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@ConditionalOnClass(com.rabbitmq.client.Channel.class)
@Configuration
public class RabbitmqConfiguration implements BeanPostProcessor {

    @Value("${project.name}")
    private String projectName;

    @Resource
    private ApplicationContext applicationContext;


    @Bean
    public QueueNameGenerator queueNameGenerator() {
        return new QueueNameGenerator();
    }


    @Bean
    public RabbitmqDomainEventPublisher rabbitmqDomainEventPublisher() {
        return new RabbitmqDomainEventPublisher();
    }

    @Bean
    public Queue defaultDomainEventQueue() {
        //队列A
        return new Queue("domain_event." + projectName, true, false, false);
    }

    @Bean
    public FanoutExchange defaultDomainEventFanoutExchange() {
        //创建FanoutExchange类型交换机
        return new FanoutExchange("domain_event_exchange_name", true, false);
    }

    @Bean
    public Binding defaultDomainEventBinding() {
        // 默认加本地绑定到本地项目
        return BindingBuilder.bind(defaultDomainEventQueue()).to(defaultDomainEventFanoutExchange());
    }

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        // 只有设置为 true，spring 才会加载 RabbitAdmin 这个类
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }


    @Bean
    public RabbitmqBeanPostProcessor rabbitmqBeanPostProcessor() {
        return new RabbitmqBeanPostProcessor();
    }

}
